package com.zxx.admin.service.base.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxx.admin.dto.code.CodeStudyDTO;
import com.zxx.admin.entity.base.CodeStudyDetailEntity;
import com.zxx.admin.entity.base.CodeStudyEntity;
import com.zxx.admin.mapper.base.CodeStudyMapper;
import com.zxx.admin.service.base.CodeStudyDetailService;
import com.zxx.admin.service.base.CodeStudyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @Description: 代码管理 服务实现
 * @author: zhuangxx
 * @date 2020-07-13
 */
@Service
public class CodeStudyServiceImpl extends ServiceImpl<CodeStudyMapper, CodeStudyEntity> implements CodeStudyService {
    @Autowired
    private CodeStudyDetailService codeStudyDetailService;

    /**
     *   新增
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addCode(CodeStudyDTO codeStudyDTO) {

        CodeStudyDetailEntity codeStudyDetailEntity = new CodeStudyDetailEntity();
        codeStudyDetailEntity.setCodeDetail(codeStudyDTO.getCodeDetail());
        String code = UUID.randomUUID().toString();
        codeStudyDetailEntity.setCodeNo(code);
        codeStudyDetailService.save(codeStudyDetailEntity);

        CodeStudyEntity codeStudyEntity = new CodeStudyEntity();
        codeStudyEntity.setCodeTitle(codeStudyDTO.getCodeTitle());
        codeStudyEntity.setCodeNo(code);
        this.save(codeStudyEntity);

        return true;
    }

    /**
     *   保存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateCode(CodeStudyDTO codeStudyDTO) {


        QueryWrapper<CodeStudyEntity> ew1 = new QueryWrapper<>();
        ew1.eq("code_no", codeStudyDTO.getCodeNo());
        CodeStudyEntity codeStudyEntity = new CodeStudyEntity();
        codeStudyEntity.setCodeTitle(codeStudyDTO.getCodeTitle());
        this.update(codeStudyEntity, ew1);

        QueryWrapper<CodeStudyDetailEntity> ew2 = new QueryWrapper<>();
        ew2.eq("code_no", codeStudyDTO.getCodeNo());
        CodeStudyDetailEntity codeStudyDetailEntity = new CodeStudyDetailEntity();
        codeStudyDetailEntity.setCodeDetail(codeStudyDTO.getCodeDetail());
        codeStudyDetailService.update(codeStudyDetailEntity, ew2);
        return true;
    }

    /**
     *   删除
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean delCode(Integer id) {

        CodeStudyEntity codeStudyEntity = this.getById(id);
        QueryWrapper<CodeStudyDetailEntity> ew2 = new QueryWrapper<>();
        ew2.eq("code_no", codeStudyEntity.getCodeNo());
        this.removeById(id);
        codeStudyDetailService.remove(ew2);
        return true;
    }
}
